package com.my.study.exception;

import com.my.study.entity.vo.ResponseVO;
import com.my.study.enums.BusinessExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalException {

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseVO<String> handleServiceException(BusinessException businessException) {
        log.error(businessException.getMessage());
        return ResponseVO.fail(Integer.valueOf(businessException.getCode()), businessException.getMsg());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseVO<String> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ResponseVO.fail(Integer.valueOf(BusinessExceptionEnum.FAIL.code),BusinessExceptionEnum.FAIL.msg);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseVO<String> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResponseVO.fail(Integer.valueOf(BusinessExceptionEnum.SYSTEM_ERROR.code), BusinessExceptionEnum.SYSTEM_ERROR.msg);
    }
}
